<?php

namespace Biz\pockets\serviceTrait;

use Doraemon\cache\Queue as cQueue;
use Doraemon\amqp\Queue as aQueue;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\Log;

/**
 * 为service提供异步操作功能
 *
 * @author luomo
 *
 */
trait _Async
{
    private static function _async()
    {
        $debugBackTrace = debug_backtrace(0, 2);
        $args = $debugBackTrace[0]["args"];
        $asyncFunction = "_async_" . $debugBackTrace[1]["function"];

        self::_async_func($asyncFunction,$args);
    }
    private static function _asyncr(){
        $debugBackTrace = debug_backtrace(0, 2);
        $args = $debugBackTrace[0]["args"];
        $asyncFunction = "_asyncr_" . $debugBackTrace[1]["function"];

        self::_async_func($asyncFunction,$args);

    }
    private static function _async_func($asyncFunction,$args){
        if (method_exists(__CLASS__, $asyncFunction)) {
            $callback = [
                __CLASS__,
                $asyncFunction
            ];

            //判断是否异步执行
            if (HhzEnv::isProduction() || HhzEnv::isGray() || HhzEnv::isTest()) {

                if (isset($_SERVER['MODULE_NAME']) && $_SERVER['MODULE_NAME'] == "Queue") {
                    call_user_func_array($callback, $args);
                } else {

 /*                   //写入队列
                    cQueue::insertQueue("queue/async/service", [
                        "callback" => $callback,
                        "params" => $args
                    ], cQueue::QUEUE_BIZ);
*/

                    //写到新队列
                    $result = aQueue::insertQueue("queue/async/service", [
                        "callback" => $callback,
                        "params" => $args
                    ], aQueue::QUEUE_BIZ);

                    return $result;
                }
            } else {
                call_user_func_array($callback, $args);
            }
        } else {
            throw new \Exception("async function not define");
        }
    }
}

